﻿using System;
using System.Configuration;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalWorkOrderIssueControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelWorkOrderIssue.ContentTemplateContainer, bstate);
        }
        public void ShowModal(int companyid, int WorkOrderid, int Issueid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Work Order Issue";

            if (LoadIssueDataByID(companyid, WorkOrderid, Issueid))
            {
                btnEditIssue.Visible = true;
                btnSaveIssue.Visible = false;
                btnDeleteIssue.Visible = false;
                SetControlEnabledState(false);
            }
            else
            {
                btnEditIssue.Visible = false;
                btnSaveIssue.Visible = true;
                btnDeleteIssue.Visible = false;
                SetControlEnabledState(true);
            }
            mpeModalWorkOrderIssue.Show();
        }
        private bool LoadIssueDataByID(int companyid, int WorkOrderid, int Issueid)
        {
            bool bHaveData = false;

            if (companyid > 0)
            {
                RSSBMDataLookupLoader.LoadAssignToCHK(companyid, chkAssignTo);
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "ISSUE_CAT", ddlIssueStatus);

                if (WorkOrderid > 0)
                {
                    int locationid = 0;
                    txtWorkOrderId.Text = WorkOrderid.ToString();
                    locationid = RSSBMCommonFunctions.GetLocationIDByWorkOrderID(companyid, WorkOrderid);
                    //ucLocationHeaderControl.LoadLocationHeader(companyid, locationid, false, false);
                    hfLocationId.Value = locationid.ToString();
                    if (Issueid > 0)
                    {
                        string strSQL = "SELECT i.IssueId, i.IssueName, i.Description, i.Response, i.IssueDT, i.CloseDT,";
                        strSQL = strSQL + " i.WorkOrderId, i.AssignTo, i.LocationId, i.StatusId, i.CompanyId";
                        strSQL = strSQL + " FROM rs_tblIssue i WHERE i.workorderid=@WorkOrderId AND i.IssueId=@IssueId";
                        strSQL = strSQL + " AND i.CompanyId=@CompanyId ORDER BY i.IssueDT DESC";

                        SqlCommand myCommand;
                        SqlParameter param;
                        SqlConnection myConnection;
                        myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                        myCommand = new SqlCommand(strSQL, myConnection);
                        SqlDataReader myDataReader;

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@Companyid";
                        param.Value = companyid;
                        myCommand.Parameters.Add(param);

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@WorkOrderid";
                        param.Value = WorkOrderid;
                        myCommand.Parameters.Add(param);

                        param = new SqlParameter();
                        param.SqlDbType = SqlDbType.Int;
                        param.ParameterName = "@Issueid";
                        param.Value = Issueid;
                        myCommand.Parameters.Add(param);

                        myConnection.Open();
                        myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                        if (myDataReader.HasRows)
                        {
                            myDataReader.Read();
                            locationid = int.Parse(myDataReader["LocationId"].ToString());
                            //ucLocationHeaderControl.LoadLocationHeader(companyid, locationid);

                            txtIssueId.Text = Issueid.ToString();
                            txtWorkOrderId.Text = myDataReader["workorderid"].ToString();
                            txtIssueName.Text = myDataReader["IssueName"].ToString();

                            if (myDataReader["IssueDT"] != DBNull.Value)
                            {
                                DateTime issuedt = Convert.ToDateTime(myDataReader["IssueDT"].ToString());
                                txtIssueTime.Text = issuedt.ToShortTimeString();
                                txtIssueDate.Text = issuedt.ToShortDateString();
                            }

                            if (myDataReader["CloseDT"] != DBNull.Value)
                            {
                                DateTime closedt = Convert.ToDateTime(myDataReader["CloseDT"].ToString());
                                txtCloseTime.Text = closedt.ToShortTimeString();
                                txtCloseDate.Text = closedt.ToShortDateString();
                            }

                            txtDescription.Text = myDataReader["Description"].ToString();
                            txtResponse.Text = myDataReader["Response"].ToString();
                            if (myDataReader["StatusId"] != DBNull.Value)
                                ddlIssueStatus.SelectedValue = myDataReader["StatusId"].ToString();

                            RSSBMCommonFunctions.SetMultiSelectList(myDataReader["AssignTo"].ToString(), chkAssignTo);
                            bHaveData = true;
                        }
                        myConnection.Close();
                    }

                }
            }
            return bHaveData;
        }
        

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected void btnSaveIssue_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;

                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value); // ucLocationHeaderControl.LocationId;
                int WorkOrderId = txtWorkOrderId.Text == "" ? 0 : Convert.ToInt32(txtWorkOrderId.Text);
                int IssueId = txtIssueId.Text == "" ? 0 : Convert.ToInt32(txtIssueId.Text);

                string IssueName = txtIssueName.Text.Trim();
                string IssueDT = txtIssueDate.Text + " " + txtIssueTime.Text.Trim();
                string CloseDT = txtCloseDate.Text + " " + txtCloseTime.Text.Trim();
                IssueDT = IssueDT.Trim();
                CloseDT = CloseDT.Trim();
                string Description = txtDescription.Text.Trim();
                string Response = txtResponse.Text.Trim();

                string AssignTo = RSSBMCommonFunctions.GetMultiSelectValue(chkAssignTo);
                int StatusID = Convert.ToInt32(ddlIssueStatus.SelectedValue);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@IssueName", SqlDbType.NVarChar, 100, ParameterDirection.Input, IssueName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@IssueDT", SqlDbType.NVarChar, 15, ParameterDirection.Input, IssueDT);

                if (CloseDT.Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@CloseDT", SqlDbType.NVarChar, 15, ParameterDirection.Input, CloseDT);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@IssueID", SqlDbType.Int, 0, ParameterDirection.Input, IssueId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AssignTo", SqlDbType.NVarChar, 100, ParameterDirection.Input, AssignTo);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@StatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderId", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveIssue");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Issue Successfully Saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnEditIssue.Visible = false;
            btnSaveIssue.Visible = false;
            btnDeleteIssue.Visible = false;
            SetControlEnabledState(false);
           
        }
        protected void btnDeleteIssue_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;
                int WorkOrderid = Convert.ToInt32(txtWorkOrderId.Text);
                int issueid = Convert.ToInt32(txtIssueId.Text);
                if(RemoveWorkOrderIssue(companyid, WorkOrderid, issueid))
                {
                    lblMessage.Text = "Issue successfully deleted!";
                    lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                    hfRedirectURL.Value = Request.RawUrl;
                }
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnEditIssue.Visible = false;
            btnSaveIssue.Visible = false;
            btnDeleteIssue.Visible = false;
            SetControlEnabledState(false);
        }
        private bool RemoveWorkOrderIssue(int companyid, int WorkOrderid, int issueid)
        {
            bool retvalue = false;
            if (companyid > 0 && WorkOrderid > 0 && issueid > 0)
            {
                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@issueid", SqlDbType.Int, 0, ParameterDirection.Input, issueid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblIssue WHERE issueid=@issueid AND workorderid=@WorkOrderid AND companyid=@companyid");
                SQLHelper.ExecuteScalarCmd(sqlCmd);
                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                retvalue = true;
            }
            return retvalue;
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            if (hfRedirectURL.Value.Length > 0)
            {
                var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                nameValues.Set("tabindex", "4");
                string url = Request.Url.AbsolutePath;
                string updatedQueryString = "?" + nameValues.ToString();
                Response.Redirect(url + updatedQueryString);
            }
            else
            {
                mpeModalWorkOrderIssue.Hide();
            }
        }
        protected void btnEditIssue_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                btnEditIssue.Visible = false;
                btnSaveIssue.Visible = true;
                btnDeleteIssue.Visible = true;
                SetControlEnabledState(true);
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                btnEditIssue.Visible = false;
                btnSaveIssue.Visible = false;
                btnDeleteIssue.Visible = false;
                SetControlEnabledState(false);
            }
        }


    }

    
}